<?php

namespace App\Models;

use App\Http\Controllers\Easemob;
use App\Service\AliCloudPushMessage;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class GroupAssistant extends Model
{
    protected $table = "c_group_assistants";


    public function setImagesAttribute($gallery)
    {
        if (is_array($gallery)) {
            $this->attributes['images'] = json_encode($gallery);
        }
    }

    public function getImagesAttribute($gallery)
    {
        return json_decode($gallery, true);
    }

    /**
     * @param $filter
     * @return string
     * 添加患教发送
     */
    public function addPatient($filter)
    {
        try {
            DB::beginTransaction(); // 开始事务
            if (!empty($filter['book_ids'])) {
                $filter['book_ids'] = Tool::handelString($filter['book_ids']);
                if (empty($filter['book_ids'])) {
                    return "通讯录ID不能为空!";
                }
            }
            //添加患教记录
            $pat_log = new PatientLog();
            $pat_log->work_id = $filter['work_id'];
            $pat_log->doctor_id = $filter['doctor_id'];
            $pat_log->patient_id = $filter['patient_id'];
            $pat_log->type = $filter['patient_type'];
            $pat_log->save();
            $pat_log_id = $pat_log->id;
            $book = (new AddressBook());
            $visit =[];
            $i = 0;
            $user_ids = [];
            foreach ($filter['book_ids'] as $k => $v) {
                $res = $book::where([['id','=',$v]])->first();
                if(empty($res)){
                    continue;
                }
                $user_ids[] = $res->user_id;
                //添加首页消息记录
                $visit[$k]['book_id']  = $v;
                $visit[$k]['user_id']  = $res->user_id;
                $visit[$k]['work_id']  = $filter['work_id'];
                $visit[$k]['doctor_id']  = $filter['doctor_id'];
//                $visit[$k]['images']  = json_encode($filter['images']);
                $visit[$k]['patient_id']  = $filter['patient_id'];
                $visit[$k]['patient_type']  = $filter['patient_type'];
                $visit[$k]['type']  = 2;
                $visit[$k]['pat_log_id']  = $pat_log_id;
//                $visit[$k]['content']  = $filter['content'];
                $visit[$k]['doctor_id']  = isset($filter['doctor_id'])?$filter['doctor_id']:0;
                $visit[$k]['created_at']  =  date("Y-m-d H:i:s",time());
                $visit[$k]['updated_at']  =  date("Y-m-d H:i:s",time());
                $i++;
            }
            $yes = DB::table('c_visit_users')->insert($visit);
            //推送消息
            $doc_info = (new Doctor())->where([['id','=',$filter['doctor_id']]])->first();
            $lit['user_id'] = implode(',',$user_ids);;
            $lit['title'] =$doc_info->real_name ."医护";
            if($filter['patient_type'] ==1){
                $lit['content'] = "向您发送了一篇文章,注意查收";
            }else{
                $lit['content'] = "向您发送了一篇课程,注意查收";
            }
            (new AliCloudPushMessage())->aliStartPush($lit);
            if($yes){
                DB::commit(); // 提交事务
                return ['visit_id' => $yes];
            }
            return "发送失败!";
        }catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }
    
    
    
    
    

    /***
     * @param $filter
     * @return array|string
     * 随访--群发
     */
    public function add($filter)
    {
        try {
            DB::beginTransaction(); // 开始事务
            if (!empty($filter['images'])) {
                $filter['images'] = Tool::handelString($filter['images']);
            }
            if (!empty($filter['book_ids'])) {
                $filter['book_ids'] = Tool::handelString($filter['book_ids']);
                if(empty($filter['book_ids'])){
                    return "通讯录ID不能为空!";
                }
            }
            $this->content = isset($filter['content']) ? $filter['content'] : "";
            $this->sound = isset($filter['sound']) ? $filter['sound'] : "";
            $this->video = isset($filter['video']) ? $filter['video'] : "";
            $this->images = isset($filter['images']) ? $filter['images'] : "";
            $this->work_id = isset($filter['work_id']) ? $filter['work_id'] : "";
            $this->doctor_id = isset($filter['doctor_id']) ? $filter['doctor_id'] :0;
            $result = $this->save();
            if ($result) {
                $dat = $this->addLogs($filter);
                if($dat){
                    DB::commit(); // 提交事务
                    return ['group_id' => $this->id];
                }
                return '发送失败';
                DB::rollback(); // 回滚事务
            } else {
                return '发送失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /***
     * @param $data
     *
     */
    public function addLogs($param)
    {
        $book = (new AddressBook());
        $data = [];
        $visit =[];
        $i = 0;
        $user_ids = [];
        foreach ($param['book_ids'] as $k => $v) {
            $res = $book::where([['id','=',$v]])->first();
            if(empty($res)){
                continue;
            }
            $data[$k]['book_id']  = $v;
            $data[$k]['work_id']  = $param['work_id'];
            $data[$k]['doctor_id']  = $param['doctor_id'];
            $data[$k]['user_id']  =$res->user_id;
            $data[$k]['type']  =1;
            $data[$k]['group_assistant_id']  =  $this->id;
            $data[$k]['created_at']  =  date("Y-m-d H:i:s",time());
            $data[$k]['updated_at']  =  date("Y-m-d H:i:s",time());
            $user_ids[] =$res->user_id; //'user' . config("omnipay.Im.salt") . $res->user_id;
            //添加首页消息记录
            $visit[$k]['book_id']  = $v;
            $visit[$k]['user_id']  = $res->user_id;
            $visit[$k]['work_id']  = $param['work_id'];
            $visit[$k]['images']  = isset($param['images'])?json_encode($param['images']):"";
            $visit[$k]['type']  = 1;
            $visit[$k]['content']  = $param['content'];
            $visit[$k]['doctor_id']  = isset($param['doctor_id'])?$param['doctor_id']:0;
            $visit[$k]['created_at']  =  date("Y-m-d H:i:s",time());
            $visit[$k]['updated_at']  =  date("Y-m-d H:i:s",time());
            $i++;
        }
        if(count($visit) >0) {
            DB::table('c_group_assistant_logs')->insert($data);
            $yes = DB::table('c_visit_users')->insert($visit);
            $this::where([['id', '=', $this->id]])->update(['num' => $i]);
            $doc_info = (new Doctor())->where([['id', '=', $visit[0]['doctor_id']]])->first();
            $lit['user_id'] = implode(',',$user_ids);
            if (!empty($doc_info)) {
                $lit['title'] = $doc_info->real_name . "医护";
            } else {
                $lit['title'] = "消息提醒";
            }
            $lit['content'] = "向您发送了一条消息";
            (new AliCloudPushMessage())->aliStartPush($lit);
        }

//        if (isset($param['images']) && !empty($param['images'])) {
//            $this->sendAllUserMes($param['images'], $user_ids,1);
//        }
//        if (isset($param['sound']) && !empty($param['sound'])) {
//            $this->sendAllUserMes($param['sound'], $user_ids,2);
//        }
//        if (isset($param['video']) && !empty($param['video'])) {
//            $this->sendAllUserMes($param['video'], $user_ids,3);
//        }
//        if (isset($param['content']) && !empty($param['content'])) {
//            $this->sendAllUserMes($param['content'], $user_ids,4);
//        }
        if($yes){
            return true;
        }
        return false;
    }

    /**
     * @param $data
     * @param $user_ids
     * @throws \Exception
     * 发送消息
     */
    public function sendAllUserMes($data, $user_ids, $type)
    {
        if ($type == 1) {
            if (is_array($data)) {
                foreach ($data as $k => $v) {
                    $file_path['file'] = $v;
                    $file = (new Easemob())->uploadFileBySdk($file_path);
                    $imgs['file_name'] = $v;
                    $imgs['file_uuid'] = $file['uuid'];
                    $imgs['secret'] = $file['share-secret'];
                    $imgs['username'] = $user_ids;
                    (new Easemob())->sendImageBySdk($imgs);
                }
            } else {
                $file_path['file'] = $data;
                $file = (new Easemob())->uploadFileBySdk($file_path);
                $imgs['file_name'] = $data;
                $imgs['file_uuid'] = $file['uuid'];
                $imgs['secret'] = $file['share-secret'];
                $imgs['username'] = $user_ids;
                (new Easemob())->sendImageBySdk($imgs);
            }
        } elseif ($type == 2) {
            if (is_array($data)) {
                foreach ($data as $k => $v) {
                    $file_path['file'] = $v;
                    $file = (new Easemob())->uploadFileBySdk($file_path);
                    $imgs['file_name'] = $v;
                    $imgs['file_uuid'] = $file['uuid'];
                    $imgs['secret'] = $file['share-secret'];
                    $imgs['username'] = $user_ids;
                    (new Easemob())->sendAudioBySdk($imgs);
                }
            } else {
                $file_path['file'] = $data;
                $file = (new Easemob())->uploadFileBySdk($file_path);
                $imgs['file_name'] = $data;
                $imgs['file_uuid'] = $file['uuid'];
                $imgs['secret'] = $file['share-secret'];
                $imgs['username'] = $user_ids;
                (new Easemob())->sendAudioBySdk($imgs);
            }
        } elseif ($type == 3) {
            if (is_array($data)) {
                foreach ($data as $k => $v) {
                    $file_path['file'] = $v;
                    $file = (new Easemob())->uploadFileBySdk($file_path);
                    $imgs['file_name'] = $v;
                    $imgs['file_uuid'] = $file['uuid'];
                    $imgs['secret'] = $file['share-secret'];
                    $imgs['username'] = $user_ids;
                    (new Easemob())->sendVideoBySdk($imgs);
                }
            } else {
                $file_path['file'] = $data;
                $file = (new Easemob())->uploadFileBySdk($file_path);
                $imgs['file_name'] = $data;
                $imgs['file_uuid'] = $file['uuid'];
                $imgs['secret'] = $file['share-secret'];
                $imgs['username'] = $user_ids;
                (new Easemob())->sendVideoBySdk($imgs);
            }
        } elseif ($type == 4) {
            $imgs['text'] = $data;
            $imgs['username'] = $user_ids;
            (new Easemob())->sendTextBySdk($imgs);
        }
        return true;
    }

    /***
     * @param $filter
     * 群发详情
     */
    public function detail($filter)
    {
        $res = $this->where([['id', '=', $filter['group_id']]])->first()->toArray();
        $host = new Url();
        $res['sound'] = !empty($res['sound']) ? $host::getHttpHost() . 'upload/' . $res['sound'] : "";
        $res['video'] = !empty($res['video']) ? $host::getHttpHost() . 'upload/' . $res['video'] : "";
        if (!empty($res['images'])) {
            foreach ($res['images'] as $k => &$v) {
                $v = $host::getHttpHost() . 'upload/' . $v;
            }
        }
        return $res;
    }





}
